package com.dzx.permissionmanagersystem.service;

import com.dzx.permissionmanagersystem.dao.SysDeptMapper;
import com.dzx.permissionmanagersystem.entity.SysDept;
import com.dzx.permissionmanagersystem.exception.ParamException;
import com.dzx.permissionmanagersystem.param.DeptParam;
import com.dzx.permissionmanagersystem.util.BeanValidator;
import com.dzx.permissionmanagersystem.util.LevelUtil;
import com.google.common.base.Preconditions;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author DuanZhaoXu
 * @ClassName:
 * @Description:
 * @date 2018年11月29日 14:06:05
 */
@Service
public class SysDeptService  {


      @Autowired
      private SysDeptMapper  mapper;

      public  void  save(DeptParam param){
          BeanValidator.check(param);
          //判断同一个层级下是否存在 同名的部门
          if(checkExist(param.getParentId(),param.getName(),param.getId())){
              throw   new ParamException("同一级下存在相同名称的部门");
          }

          SysDept  sysDept = SysDept.builder().name(param.getName()).parentId(param.getParentId())
            .seq(param.getSeq()).remark(param.getRemark()).build();

          sysDept.setLevel(LevelUtil.calculateLevel(getLevel(param.getParentId()),param.getParentId()));

          sysDept.setOperator("system"); //TODO
          sysDept.setOperateIp("127.0.0.1");
          sysDept.setOperateTime(new Date());

          mapper.insertSelective(sysDept);

      }


      public  boolean  checkExist(Integer parentId,String name,Integer deptId){
          return mapper.countByNameAndParentId(parentId,name,deptId)>0;
      }


      private  String  getLevel (Integer deptId){
          SysDept dept =  mapper.selectByPrimaryKey(deptId);
          if(dept==null){
              return null;
          }
          return dept.getLevel();
      }


    public void update(DeptParam param) {
        BeanValidator.check(param);
        //判断同一个层级下是否存在 同名的部门
        if(checkExist(param.getParentId(),param.getName(),param.getId())){
            throw   new ParamException("同一级下存在相同名称的部门");
        }

        SysDept  before = mapper.selectByPrimaryKey(param.getId());
        Preconditions.checkNotNull(before,"待更新的部门不存在");
        //判断同一个层级下是否存在 同名的部门
        if(checkExist(param.getParentId(),param.getName(),param.getId())){
            throw   new ParamException("同一级下存在相同名称的部门");
        }
        SysDept after =  SysDept.builder().id(param.getId()).name(param.getName()).parentId(param.getParentId())
                .seq(param.getSeq()).remark(param.getRemark()).build();

        after.setLevel(LevelUtil.calculateLevel(getLevel(param.getParentId()),param.getParentId()));

        after.setOperator("system"); //TODO
        after.setOperateIp("127.0.0.1");
        after.setOperateTime(new Date());

        updateWithChild(before,after);


    }


    @Transactional
    private  void  updateWithChild(SysDept before,SysDept after){
          mapper.updateByPrimaryKey(after);

          String newLevelPrefix = after.getLevel();
          String oldLevelPrefix = before.getLevel();

          if(!newLevelPrefix.equals(oldLevelPrefix)){
            List<SysDept>  deptList= mapper.getChildDeptListByLevel(oldLevelPrefix);
            if(CollectionUtils.isNotEmpty(deptList)){
                for(SysDept dept:deptList){
                    String level = dept.getLevel();
                    if(level.indexOf(oldLevelPrefix) ==0 ){
                          level = newLevelPrefix + level.substring(oldLevelPrefix.length());
                          dept.setLevel(level);
                    }
                }
                mapper.batckUpdateLevel(deptList);
            }
          }
    }
}
